package com.example.codeanalysis;

import com.example.codeanalysis.parser.AnaResult;
import com.example.codeanalysis.parser.JavaSourceParser;
import com.example.codeanalysis.parser.ResultDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Collection;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.FileWriterWithEncoding;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@Slf4j
@SpringBootApplication
public class CodeAnaApplication {

  public static void main(String[] args) {
    commandLineParse(args);
    SpringApplication.run(CodeAnaApplication.class, args);
  }

  /**
   * 如果运行时制定了启动参数，可以从启动参数解析源码
   * @param args 0-sysCode,1-subSysCode,2-localJavaSourcePath
   */
  private static void commandLineParse(String[] args) {
    try {
      if (args.length >= 3) {
        JavaSourceParser parser = new JavaSourceParser(args[0], args[1], args[2]);
        List<AnaResult> resultList = parser.parse();
        FileWriterWithEncoding fileWrite = new FileWriterWithEncoding(args[1] + ".txt", "UTF-8");
        IOUtils.write("sysCode: " + args[0] + ", subSysCode: " + args[1], fileWrite);
        for (AnaResult result : resultList) {
          IOUtils.write(result.toString(), fileWrite);
        }
        fileWrite.close();

        ResultDTO dto = new ResultDTO();
        dto.setTotalApiCount(resultList.stream()
            .map(AnaResult::getApis)
            .mapToLong(Collection::size)
            .sum());
        dto.setData(resultList);
        dto.setSysCode(args[0]);
        dto.setSubSysCode(args[1]);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(dto);
        fileWrite = new FileWriterWithEncoding(args[1] + ".json", "UTF-8");
        IOUtils.write(json, fileWrite);
        fileWrite.close();
      }
    } catch (Exception e) {
      log.error(e.getMessage());
    }
  }

}
